package com.jk.garden1.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jk.garden1.dao.CompanyDao;
import com.jk.garden1.dao.EsCompanyDao;
import com.jk.garden1.dao.StaffDao;
import com.jk.garden1.entity.BuildingEntity;
import com.jk.garden1.entity.CompanyEntity;
import com.jk.garden1.entity.StaffEntity;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * 公司管理
 */
@Service
public class CompanyService {
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private ElasticsearchRestTemplate es;
    @Autowired
    private EsCompanyDao esCompanyDao;
    @Autowired
    private StaffDao staffDao;


    //定义验证码
    public static String charactercode = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    /**
     * 调差查询
     * @param company
     * @return
     */
    public List<CompanyEntity> selectListCompanys(CompanyEntity company) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("state", company.getState());
        return companyDao.selectList(queryWrapper);

    }
    /**
     * 查询全部
     * @param company
     */
    public List<CompanyEntity> selectListCompany(CompanyEntity company) {
        QueryWrapper<CompanyEntity> wrapper = new QueryWrapper<>();
        List<CompanyEntity> companyEntities = companyDao.selectList(wrapper);
        return companyEntities;
    }
    /**
     * 添加公司
     */
    public void addCompany(CompanyEntity companyEntity) {
        StringBuilder stringBuilder = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            stringBuilder.append(charactercode.charAt(random.nextInt(6)));
        }
        companyEntity.setCompanycode(stringBuilder.toString());
        companyEntity.setState("正常");
        companyDao.insert(companyEntity);
    }

    /**
     * 停用
     * @param id
     */
    public void updateById(Integer id) {
        CompanyEntity companyEntity = companyDao.selectById(id);
        companyEntity.setState("已停用");
        companyDao.updateById(companyEntity);
    }

    /**
     * 注销
     * @param id
     */
    public void updateByIds(Integer id) {
        CompanyEntity companyEntity = companyDao.selectById(id);
        companyEntity.setState("已注销");
        companyDao.updateById(companyEntity);
    }

    public CompanyEntity queryCompanyOne(String companycode) {
        return companyDao.queryCompanyOne(companycode);
    }

    /**
     * 新建索引
     */
    public void create(){
        es.createIndex(CompanyEntity.class);
        QueryWrapper wp=new QueryWrapper();
        List<CompanyEntity> list = companyDao.selectList(wp);
        list.forEach(a -> {
            esCompanyDao.save(a);
        });
    }
    /**
     * es高亮查询
     * @param company
     * @return
     */

    public Object queryEsList(CompanyEntity company) {
        if (es.indexExists(CompanyEntity.class)){
            create();
        }
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        //公司码精确查
        if(StringUtils.hasText(company.getCompanycode())){
            nativeSearchQueryBuilder.withQuery(QueryBuilders.termQuery("companycode",company.getCompanycode()));
        }
        //负责人手机号精确查
        if(StringUtils.hasText(company.getPrincipalphone())){
            nativeSearchQueryBuilder.withQuery(QueryBuilders.termQuery("principalphone",company.getPrincipalphone()));
        }
        //公司名称模糊查
        if(StringUtils.hasText(company.getCompanyname())){
            nativeSearchQueryBuilder.withQuery(QueryBuilders.matchQuery("companyname",company.getCompanyname()))
                    .withHighlightFields(new HighlightBuilder.Field("companyname").preTags("<font color='red'>").postTags("</font>"));
        }
        //负责人姓名模糊查
        if(StringUtils.hasText(company.getPrincipalname())){
            nativeSearchQueryBuilder.withQuery(QueryBuilders.matchQuery("principalname",company.getPrincipalname()))
                    .withHighlightFields(new HighlightBuilder.Field("principalname").preTags("<font color='red'>").postTags("</font>"));
        }
        SearchQuery build = nativeSearchQueryBuilder.build();
        if(StringUtils.hasText(company.getPrincipalname())){
            AggregatedPage<CompanyEntity> employeeEntity = es.queryForPage(build, CompanyEntity.class, new SearchResultMapper() {
                @Override
                public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
                    SearchHits hits = searchResponse.getHits();
                    List list = new ArrayList();
                    for (SearchHit hit : hits) {
                        Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                        Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                        sourceAsMap.put("principalname", highlightFields.get("principalname").getFragments()[0].toString());
                        list.add(sourceAsMap);
                    }
                    return new AggregatedPageImpl<>(list);
                }
                @Override
                public <T> T mapSearchHit(SearchHit searchHit, Class<T> aClass) {
                    return null;
                }
            });
            return employeeEntity.getContent();
        }else if(StringUtils.hasText(company.getCompanyname())){
            AggregatedPage<CompanyEntity> employeeEntity = es.queryForPage(build, CompanyEntity.class, new SearchResultMapper() {
                @Override
                public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
                    SearchHits hits = searchResponse.getHits();
                    List list = new ArrayList();
                    for (SearchHit hit : hits) {
                        Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                        Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                        sourceAsMap.put("companyname", highlightFields.get("companyname").getFragments()[0].toString());
                        list.add(sourceAsMap);
                    }
                    return new AggregatedPageImpl<>(list);
                }
                @Override
                public <T> T mapSearchHit(SearchHit searchHit, Class<T> aClass) {
                    return null;
                }
            });
            return employeeEntity.getContent();
        }else{
            List<CompanyEntity> list2 = es.queryForList(build, CompanyEntity.class);
            return  list2;
        }
    }
    /**
     * 查询楼层入住公司信息
     * @param ubietylevel
     * @return
     */
    public Integer findlistById(String ubietylevel) {
        QueryWrapper<CompanyEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("ubietylevel",ubietylevel);
        Integer aLong = Math.toIntExact(companyDao.selectCount(wrapper));
        System.out.println("aLong = " + aLong);
        return aLong;
    }

    public Object findlistByIds(Integer companyid) {
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("companyid",companyid);
        List<StaffEntity> staffEntities = staffDao.selectList(wrapper);

        return staffEntities;

    }

    public Object selectbucode(CompanyEntity company) {
        QueryWrapper<CompanyEntity> wrapper = new QueryWrapper();
        wrapper.eq("companycode",company.getCompanycode());
        List list = companyDao.selectList(wrapper);
        return list;
    }
}
